library(haven)
library(ggplot2)
library(tidyr)
library(dplyr)
library(stringr)
library(labelled)
library(texreg)
library(zoo)

setwd("C:/Users/jonves/Dropbox/Papers/SSP-Instability-Opinion/replication_data/")

df <- read_dta("data/BazziBlattman-Replication-Final/Data/commod_data_BazziBlattman.dta")
#df <- read_dta("data/BazziBlattman-Replication-Final/Data/BAZZI_BLATTMAN_FINAL.dta")


agg <- group_by(df, country_code_iso3c) %>%
  arrange(year) %>%
  summarize(ppx = mean(ppx, na.rm = T),
            ppx_no_ff = mean(ppx*(1-iw_g_oil)*(1-iw_gas), na.rm=T))


pwt <- read_dta("data/pwt90.dta")
pwt$gdpcap <- pwt$rgdpna / pwt$pop
growth <- function(x){x/lag(x)-1}

pwt <- group_by(pwt, countrycode) %>%
  arrange(year) %>%
  mutate(grwt = growth(gdpcap)) %>%
  summarize(ngrwtr = mean(grwt < 0, na.rm = T))

agg <- left_join(agg, pwt, by=c("country_code_iso3c" = "countrycode"))
agg$ppx <- if_else(agg$ppx > 1, 1, agg$ppx)
agg$ppx_no_ff <- if_else(agg$ppx_no_ff > 1, 1, agg$ppx_no_ff)

# The anomalies on the left (0.65 (DJI), .53 (HTI) and .38 (BGD) are due to reexports and clothing). All countries have seen civil wars.

ggplot(agg, aes(y=ngrwtr, x=ppx_no_ff)) + geom_point() + geom_smooth(method="lm") + 
  xlab("Primary Products as % of Exports") + 
  ylab("Share of years with negative growth")

p1 <- ggplot(agg, aes(y=ngrwtr, x=ppx)) + geom_point() + 
  geom_smooth(method="lm", se=FALSE, color="red") +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  scale_x_continuous(labels = scales::percent_format(accuracy = 1)) +
  xlab("Primary products as % of exports") + 
  ylab("Share of years with negative growth (PWT 9.0, 1950-2014)") +
  theme_bw() +
  theme(strip.text.x = element_text(size=14),
        axis.title = element_text(size=14),
        axis.text = element_text(size=14))

ggsave("results/figure4a.tiff", plot=p1, width=6, height=6, dpi=300, compression="zip")
